import { ILocalAudioTrack } from "agora-rtc-sdk-ng";

/*
 * @Author: sdq 483657864@qq.com
 * @Date: 2025-04-18 15:35:59
 * @LastEditors: sdq 483657864@qq.com
 * @LastEditTime: 2025-04-19 15:37:50
 * @FilePath: \ranyu_anchor_new\src\agroa\joinAndleave\index.ts
 * @Description: 用户加入频道和离开
 */
export const agoraJoinAndLeave = async () => {
  const { useAudioStore } = await import("@/store");
  const { agoraClient } = await import("../initAgoraSdk");
  const { handleError, resetState } = await import("../auxiliary");
  const { useVoiceConfigStore } = await import("@/store");
  const { useLiveStatusStore } = await import("@/store");
  const audioStore = useAudioStore();
  const voiceConfigStore = useVoiceConfigStore();
  const liveStatusStore = useLiveStatusStore();
  /**
   * 加入语音频道
   * @description 根据配置参数连接至指定频道
   * @throws 加入失败时抛出错误
   */
  const join = async () => {
    if (!agoraClient.value) throw new Error("客户端未初始化");
    try {
      // 严格遵循参数顺序：appId, channel, token, uid
      await agoraClient.value.join(
        voiceConfigStore.appId,
        voiceConfigStore.channel,
        voiceConfigStore.token,
        voiceConfigStore.uid
      );
      // 设置用户角色（需在加入频道后调用）
      await agoraClient.value.setClientRole(voiceConfigStore.role);
      liveStatusStore.changeJoinStatus(true);
      ElMessage.success("加入频道成功");
    } catch (error) {
      handleError("加入失败", error);
      throw error;
    }
  };
  /**
   * 离开频道并清理所有资源
   * @description 安全断开与频道的连接，释放所有音频资源
   */
  const leave = async () => {
    if (!agoraClient.value || !liveStatusStore.isJoined) return;
    try {
      // // // 停止推流
      // await unpublishTrack("mic");
      // await unpublishTrack("system");
      // 离开频道
      await agoraClient.value.leave();
      // 关闭所有本地音频轨道
      audioStore.mic?.close();
      audioStore.system?.close();
      // 重置状态
      resetState();
      //显示反馈
      ElMessage.success("已成功离开频道");
    } catch (error) {
      // 错误处理
      handleError("离开频道失败", error);
      throw error; // 抛出错误供上层处理
    }
  };
  const unpublishTrack = async (type: "mic" | "system") => {
    try {
      if (type === "mic" && agoraClient.value) {
        if (!audioStore.mic) return;
        await agoraClient.value?.unpublish(audioStore.mic as ILocalAudioTrack);
        audioStore.setMic(undefined);
      } else {
        if (!audioStore.system) return;
        audioStore.setSystem(undefined);
        await agoraClient.value?.unpublish(audioStore.system as ILocalAudioTrack);
      }
    } catch (error) {
      handleError("取消发布失败", error);
    }
  };
  return {
    join,
    leave,
    unpublishTrack,
  };
};
